package com.jiang.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.jiang.vo.Member;

@Controller
public class LoginAction {

	@RequestMapping("/shiroLogin")
	public ModelAndView Login(Member member, HttpServletRequest request) {

		ModelAndView mav = new ModelAndView();
		Subject sub = SecurityUtils.getSubject();
		try {
			UsernamePasswordToken token = new UsernamePasswordToken(member.getMid(), member.getPassword());
			// 验证密码前先进行验证码验证
			String code = request.getParameter("code");
			HttpSession session = request.getSession();
			if (StringUtils.isBlank(code) || !code.equals(session.getAttribute("rand"))) { // 默认的放入session中的验证码的名称为rand
				mav.setViewName("login");
				System.out.println("验证码错误!!");
				return mav;
			}
			sub.login(token);
			System.out.println(sub.getSession().getHost()); // 主机名
			System.out.println(sub.getSession().getId()); // sessionid
			System.out.println(sub.getPrincipal()); // 用户名
			System.out.println(sub.getSession().getLastAccessTime()); // 最后一次访问时间
			System.out.println(sub.getSession().getTimeout()); // session超时时间
			System.out.println(sub.getSession().getStartTimestamp()); // session启动时间
			mav.setViewName("welcome");
		} catch (Exception e) {
			e.printStackTrace();
			mav.setViewName("login");
		}
		return mav;
	}

	@RequestMapping("/loginUrl")
	public ModelAndView loginUrl() {

		return new ModelAndView("login");
	}

	@RequestMapping("/unauthUrl")
	public ModelAndView unauthorizedUrl() {

		return new ModelAndView("role");
	}

	// @RequestMapping("/successUrl")
	// public ModelAndView successUrl(){
	//
	// return new ModelAndView("welcome");
	// }
}
